import { reactive, toRefs, watch } from 'vue'
import { useRoute } from 'vue-router'
import { searchApi } from '@/api'
export default function() {
  const route = useRoute()
  const state = reactive({
    hots: []
  })
  // 获取热门搜索关键字
  const getHotSearch = async () => {
    try {
      if (state.hots.length) {
        return
      }
      const { list } = await searchApi.getHotSearch()
      if (Array.isArray(list)) {
        state.hots = list.slice(0, 8)
      }
    } catch (error) {
      console.log(error)   
    }
  }

  watch(() => route.query, (newVal) => {
    if (route.name === 'search') {
      const { keyword } = newVal
      if (!keyword) {
        getHotSearch()
      }        
    }
  }, {
    immediate: true
  })

  return {
    ...toRefs(state)
  }
}